package com.purplesoft.zettl.Activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.purplesoft.zettl.R;
import com.purplesoft.zettl.Adapters.EditCategoriesListAdapter;
import com.purplesoft.zettl.Database.DatabaseExecuter;
import com.purplesoft.zettl.DatabaseTables.TblCategories;
import com.purplesoft.zettl.DatabaseTables.TblItems;

public class EditCategories extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {

	private ListView lvCategories;
	private ImageButton btAddNewCategory;
	private TextView tvCategory, tvCurrentCategoryColor, tvAddNewCategory, tvCategoryColorPicker;
	private EditText etCategory;
	private Button btCancel;
	private Cursor csTblCategories;
	private EditCategoriesListAdapter laCategories;
	private Dialog editCategoryDialog;
	private AlertDialog alertDialogCategory;
	private DatabaseExecuter dbExec;
	private String category, selectedCategoryColor = null;
	private final int OK_BUTTON = 1, YES_NO_BUTTON = 2;
	private final int CATEGORY_ID_DEFAULT_VALUE = -99;
	private final String EQUAL_OPERATION = " = ", NOT_EQUAL_OPERATION = " != ";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(R.style.Theme_Purple);
		setContentView(R.layout.edit_category);
        
		lvCategories = (ListView) findViewById(R.id.lvCategories_EditCategory);
		btAddNewCategory = (ImageButton) findViewById(R.id.btAddCategory_EditCategory);
		tvAddNewCategory = (TextView) findViewById(R.id.tvAddNewCategory_EditCategory);
		btCancel = (Button) findViewById(R.id.btCancel_EditCategory);
		
		dbExec = new DatabaseExecuter(this);
		
		selectDataForLvLists();
		btAddNewCategory.setOnClickListener(this);
		tvAddNewCategory.setOnClickListener(this);
		btCancel.setOnClickListener(this);
	}

	private void selectDataForLvLists() {
		csTblCategories = dbExec.queryFromTblCategories(TblCategories.Columns._ID, CATEGORY_ID_DEFAULT_VALUE, NOT_EQUAL_OPERATION);
		startManagingCursor(csTblCategories);
		laCategories = new EditCategoriesListAdapter(this, csTblCategories);
		lvCategories.setAdapter(laCategories);
	}

	public void onClick(View view) {
		switch(view.getId()) {
		case R.id.btAddCategory_EditCategory:
			showEditCategoryDialog(null);
			break;
		case R.id.tvAddNewCategory_EditCategory:
			showEditCategoryDialog(null);
			break;
		case R.id.btCancel_EditCategory:
			finish();
			break;
		case R.id.btSave_EditCategoryDialog:
			saveCategory();
			break;
		case R.id.btCancel_EditCategoryDialog:
			category = null;
			selectedCategoryColor = null;
			editCategoryDialog.dismiss();
			break;
		}
	}
	
	public void selectCategory(View view) {
		RelativeLayout editCategoryRow = (RelativeLayout) view.getParent();
		tvCategory = (TextView) editCategoryRow.findViewById(R.id.tvCategory_EditCategoryRow);
		category = tvCategory.getText().toString();
		csTblCategories = dbExec.queryFromTblCategories(TblCategories.Columns.CategoryName, category, EQUAL_OPERATION);
		startManagingCursor(csTblCategories);
		Bundle resultBundle = new Bundle();
		resultBundle.putString(TblCategories.Columns.CategoryName, category);
		resultBundle.putInt(TblCategories.Columns._ID, csTblCategories.getInt(csTblCategories.getColumnIndex(TblCategories.Columns._ID)));
		Intent resultIntent = new Intent().putExtras(resultBundle);
		setResult(RESULT_OK, resultIntent);
		finish();
	}
	
	public void selectCategoryColor(View view) {
		selectedCategoryColor = (String) view.getTag();
		int height = view.getLayoutParams().height;
		int width = view.getLayoutParams().width;
		int x = view.getLeft();
		int y = view.getTop();
		tvCurrentCategoryColor.setBackgroundColor(Color.parseColor(selectedCategoryColor));
		tvCurrentCategoryColor.setText(null);
		tvCategoryColorPicker.setVisibility(View.VISIBLE);

		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(height, width);
		layoutParams.leftMargin = x;
		layoutParams.topMargin = y;
		tvCategoryColorPicker.setLayoutParams(layoutParams);

	}
	
	public void editCategory(View view) {
		RelativeLayout editCategoryRow = (RelativeLayout) view.getParent();
		tvCategory = (TextView) editCategoryRow.findViewById(R.id.tvCategory_EditCategoryRow);
		category = tvCategory.getText().toString();
		showEditCategoryDialog(category);
	}

	public void deleteCategory(View view) {
		RelativeLayout editCategoryRow = (RelativeLayout) view.getParent();
		tvCategory = (TextView) editCategoryRow.findViewById(R.id.tvCategory_EditCategoryRow);
		category = tvCategory.getText().toString();
		showAlertDialog(getResources().getString(R.string.delete_category), YES_NO_BUTTON);
	}
	
	private boolean checkIfAllFieldsAreFilled() {
		if (etCategory.getText().toString().equals("")) {
			showAlertDialog(getResources().getString(R.string.fill_in_category), OK_BUTTON);
			return false;
		} else if (selectedCategoryColor == null) {
			showAlertDialog(getResources().getString(R.string.select_category_color), OK_BUTTON);
			return false;
		} else {
			return true;
		}
	}

	private void saveCategory() {
		if (checkIfAllFieldsAreFilled() == false) return;
		if (category !=null) {
			if (dbExec.updateTblCategories(category, etCategory.getText().toString(), selectedCategoryColor) == false) {
				showAlertDialog(getResources().getString(R.string.category_already_exists), OK_BUTTON);
				etCategory.selectAll();
				return;
			}
		} else {
			if (dbExec.insertIntoTblCategories(etCategory.getText().toString(), selectedCategoryColor) == false) {
				showAlertDialog(getResources().getString(R.string.category_already_exists), OK_BUTTON);
				etCategory.selectAll();
				return;
			}
		}
			category = null;
			selectDataForLvLists();
			editCategoryDialog.dismiss();
	}

	private void showAlertDialog(String alertText, int buttons) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch(buttons) {
		case OK_BUTTON:
			builder.setMessage(alertText);
			builder.setNeutralButton(R.string.ok, this);
			break;
		case YES_NO_BUTTON:
			builder.setMessage(String.format(alertText, category));
			builder.setCancelable(false);
		    builder.setPositiveButton(R.string.yes, this);
		    builder.setNegativeButton(R.string.no, this);
		    break;
		}
		if (alertDialogCategory == null || !alertDialogCategory.isShowing()) {
			alertDialogCategory = builder.create();
			alertDialogCategory.show();
		}
	}

	private void showEditCategoryDialog(String category) {
		RelativeLayout viewGroup = (RelativeLayout) findViewById(R.id.EditCategoryDialog);
		LayoutInflater layoutInfater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View layout = layoutInfater.inflate(R.layout.edit_category_dialog, viewGroup);
		
		if (editCategoryDialog == null || !editCategoryDialog.isShowing()) {
			editCategoryDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
			editCategoryDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			editCategoryDialog.setContentView(layout);
			
			WindowManager.LayoutParams lp = editCategoryDialog.getWindow().getAttributes();
			lp.dimAmount=0.6f;
			editCategoryDialog.getWindow().setAttributes(lp);  
			editCategoryDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
			editCategoryDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
			
			Button btSaveEditCategoryDialog = (Button) editCategoryDialog.findViewById(R.id.btSave_EditCategoryDialog);
			Button btCancelEditCategoryDialog = (Button) editCategoryDialog.findViewById(R.id.btCancel_EditCategoryDialog);
			TextView tvTitleEditCategoryDialog = (TextView) editCategoryDialog.findViewById(R.id.tvTitle_EditCategoryDialog);
			tvCurrentCategoryColor = (TextView) editCategoryDialog.findViewById(R.id.ivCurrentCategoryColor_EditCategoryDialog);
			tvCategoryColorPicker = (TextView) editCategoryDialog.findViewById(R.id.tvCategoryColorPicker_EditCategoryDialog);
			etCategory = (EditText) editCategoryDialog.findViewById(R.id.etCategory_EditCategoryDialog);
			
			if (category != null) {
				csTblCategories = dbExec.queryFromTblCategories(TblCategories.Columns.CategoryName, category, EQUAL_OPERATION);
				startManagingCursor(csTblCategories);
				tvTitleEditCategoryDialog.setText(getResources().getString(R.string.edit_category));
				etCategory.setText(category);
				tvCurrentCategoryColor.setBackgroundColor(Color.parseColor(csTblCategories.getString(csTblCategories.getColumnIndex(TblCategories.Columns.CategoryColor))));
				tvCurrentCategoryColor.setText(null);
				etCategory.selectAll();
				btSaveEditCategoryDialog.setText(R.string.alter);
			}
			
			btSaveEditCategoryDialog.setOnClickListener(this);
			btCancelEditCategoryDialog.setOnClickListener(this);
			
			editCategoryDialog.show();
		}
	}

	public void onClick(DialogInterface dialog, int which) {
		switch(which) {
		case -1: // Yes
				csTblCategories = dbExec.queryFromTblCategories(TblCategories.Columns.CategoryName, category, EQUAL_OPERATION);
				startManagingCursor(csTblCategories);
				dbExec.updateTblItems(TblItems.Columns.CategoryID, csTblCategories.getInt(csTblCategories.getColumnIndex(TblCategories.Columns._ID)), CATEGORY_ID_DEFAULT_VALUE);
				dbExec.deleteFromTblCategories(category);
				selectDataForLvLists();
				Toast.makeText(this, String.format(getResources().getString(R.string.category_deleted), category), Toast.LENGTH_LONG).show();
				category = null;
		}
	}
}
